package ch.comtools.servermanager.ssh.action;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import ch.comtools.servermanager.ssh.core.SessionInfo;
import ch.comtools.servermanager.ssh.ui.editor.TerminalEditor;
import ch.comtools.servermanager.ssh.ui.editor.input.TerminalEditorInput;
import ch.comtools.servermanager.ssh.ui.wizard.SecureShellConnectionWizard;

/**
 * @author Roger Dudler <roger.dudler@gmail.com>
 * @version $Id$
 * @see IWorkbenchWindowActionDelegate
 */
public class OpenTerminalAction implements IWorkbenchWindowActionDelegate {
	
	private IWorkbenchWindow window;
	
	/**
	 * The constructor.
	 */
	public OpenTerminalAction() {
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		try {
			
			// initialize session information (user, etc.)
			SessionInfo info = new SessionInfo();
			
			// gather connection information
			SecureShellConnectionWizard wizard = new SecureShellConnectionWizard();
			WizardDialog wizardDialog = new WizardDialog(window.getShell(), wizard);
			wizardDialog.open();
			if (wizardDialog.getReturnCode() == WizardDialog.OK) {
				
				// fill session information
				info.setHost(wizard.getHost());
				info.setUser(wizard.getUser());
				info.setPassword(wizard.getPassword());
				info.setPort(wizard.getPort());
				
				// open terminal
				TerminalEditorInput input = new TerminalEditorInput(wizard.getLabel());
				IEditorPart part = page.openEditor(input, "ch.comtools.servermanager.ssh.editor.terminal");
				TerminalEditor editor = (TerminalEditor) part;
				editor.setSessionInfo(info);
			}
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Selection in the workbench has been changed. We 
	 * can change the state of the 'real' action here
	 * if we want, but this can only happen after 
	 * the delegate has been created.
	 * @see IWorkbenchWindowActionDelegate#selectionChanged
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}

	/**
	 * We can use this method to dispose of any system
	 * resources we previously allocated.
	 * @see IWorkbenchWindowActionDelegate#dispose
	 */
	public void dispose() {
	}

	/**
	 * We will cache window object in order to
	 * be able to provide parent shell for the message dialog.
	 * @see IWorkbenchWindowActionDelegate#init
	 */
	public void init(IWorkbenchWindow window) {
		this.window = window;
	}
}